////
////  ThirdPartWechat.m
////  Screen
////
////  Created by Season02 on 7/19/16.
////  Copyright © 2016 Season02. All rights reserved.
////
//
//#import "ThirdPartAlipay.h"
//#import "ThirdPartWechat.h"
//#import "LoginThirdpartyKeys.h"
//#import "AFNetworking.h"
////#import "MGCTabBarController.h"
////#import "MGCLoginRegisterViewController.h"
//#import "WechatEntity.h"
//#import "SeAlertView.h"
//
//#import "ThirdDefine.h"
//
////
//
//static bool* payView;
//static NSString* buyhistoryid;
//
//static UIViewController* reactView;
//
//@implementation ThirdPartWechat
//
//-(void)prepareToLogin
//{
//    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:kWeiXinAccessToken];
//    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:kWeiXinOpenId];
//    //     如果已经请求过微信授权登录，那么考虑用已经得到的access_token
//    if (!accessToken && openID)
//    {
//        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:kWeiXinRefreshToken];
//        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", kWeixinBaseUrl, kWeiXinAppId, refreshToken];
//        
//        //发送请求
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//        [manager GET:refreshUrlStr parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
//         {
//             NSLog(@"请求reAccess的response = %@", responseObject);
//             NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
//             NSString *reAccessToken = [refreshDict objectForKey:@"access_token"];
//             // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
//             if (reAccessToken)
//             {
//                 // 更新access_token、refresh_token、open_id
//                 [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:kWeiXinAccessToken];
//                 [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:@"openid"] forKey:kWeiXinOpenId];
//                 [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:@"refresh_token"] forKey:kWeiXinRefreshToken];
//                 [[NSUserDefaults standardUserDefaults] synchronize];
//                 // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
//                 //!self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
//             }
//             else
//             {
//                 [self riseLogin];
//             }
//         }
//             failure:^(NSURLSessionTask *operation, NSError *error)
//         {
//             NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
//         }];
//        
//    }
//    else
//    {
//        [self riseLogin];
//    }
//}
//
//+(BOOL)installed
//{
//    return [WXApi isWXAppInstalled];
//}
//
////+(void)shareToFriend:(MGCMedias*)media
////{
////    WXMediaMessage *message = [WXMediaMessage message];
////    message.title = media.title;
////    
////    //[message setThumbImage:[UIImage ]];
////    
////    WXWebpageObject *webpageObject = [WXWebpageObject object];
////    webpageObject.webpageUrl = [NSString stringWithFormat:@"%@%@", VPrifix, media.vid];
////    message.mediaObject = webpageObject;
////    
////    [message setThumbImage:[self handleImageWithURLStr:media.picMinPath]];
////    
////    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
////    req.bText = NO;
////    req.message = message;
////    req.scene = WXSceneSession;
////    
////    [WXApi sendReq:req];
////}
//
//+(void)shareToFriend:(ShareType)type eid:(NSString*)eid title:(NSString*)title url:(NSString*)url
//{
//    WXMediaMessage *message = [WXMediaMessage message];
//    message.title = title;
//    
//    [message setThumbImage:[self handleImageWithURLStr:url]];
//    
//    WXWebpageObject *webpageObject = [WXWebpageObject object];
//    webpageObject.webpageUrl = [CommonShare GenerateUrl:type eid: eid];
//    message.mediaObject = webpageObject;
//    
//    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
//    req.bText = NO;
//    req.message = message;
//    req.scene = WXSceneSession;
//    
//    [WXApi sendReq:req];
//}
//
//
////+(void)shareToTimeLine:(MGCMedias*)media
////{
////    WXMediaMessage *message = [WXMediaMessage message];
////    message.title = media.title;
////    
////    //[message setThumbImage:[UIImage ]];
////    
////    WXWebpageObject *webpageObject = [WXWebpageObject object];
////    webpageObject.webpageUrl = [NSString stringWithFormat:@"%@%@", VPrifix, media.vid];
////    message.mediaObject = webpageObject;
////    
////    [message setThumbImage:[self handleImageWithURLStr:media.picMinPath]];
////    
////    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
////    req.bText = NO;
////    req.message = message;
////    req.scene = WXSceneTimeline;
////    
////    [WXApi sendReq:req];
////}
//
//+(void)shareToTimeLine:(ShareType)type eid:(NSString*)eid title:(NSString*)title url:(NSString*)url
//{
//    WXMediaMessage *message = [WXMediaMessage message];
//    message.title = title;
//    
//    WXWebpageObject *webpageObject = [WXWebpageObject object];
//    webpageObject.webpageUrl = [CommonShare GenerateUrl:type eid: eid];//[NSString stringWithFormat:@"%@%@", pri, eid];
//    message.mediaObject = webpageObject;
//    
//    [message setThumbImage:[self handleImageWithURLStr:url]];
//    
//    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
//    req.bText = NO;
//    req.message = message;
//    req.scene = WXSceneTimeline;
//    
//    [WXApi sendReq:req];
//}
//
//+(UIImage *)handleImageWithURLStr:(NSString *)imageURLStr
//{
//    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: imageURLStr]];
//    NSData *newImageData = imageData;
//    // 压缩图片data大小
//    newImageData = UIImageJPEGRepresentation([UIImage imageWithData:newImageData scale:0.1], 0.1f);
//    UIImage *image = [UIImage imageWithData:newImageData];
//    
//    // 压缩图片分辨率(因为data压缩到一定程度后，如果图片分辨率不缩小的话还是不行)
//    CGSize newSize = CGSizeMake(200, 200);
//    UIGraphicsBeginImageContext(newSize);
//    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newImage;
//}
//
//-(void)riseLogin
//{
//    SendAuthReq *req = [[SendAuthReq alloc] init];
//    req.scope = @"snsapi_userinfo";
//    req.state = kAppDescription;
//    [WXApi sendReq:req];
//}
//
////+(void)setupPayView:(MGCPayViewController*)view
////{
////    payView = view;
////}
//
//+(void)setupView:(UIViewController*)view
//{
//    reactView = view;
//}
//
//+(void)setBuyHistoryId:(NSString*)buyhistory
//{
//    buyhistoryid = buyhistory;
//}
//
//+(void)risePay:(NSDictionary*)para
//{
//    PayReq *request   = [[PayReq alloc] init];
//    request.partnerId = [para objectForKey:@"partnerid"];
//    request.prepayId  = [para objectForKey:@"prepayid"];
//    request.package   = [para objectForKey:@"package"];
//    request.nonceStr  = [para objectForKey:@"noncestr"];
//    request.timeStamp = [[para objectForKey:@"timestamp"] intValue];
//    request.sign      = [para objectForKey:@"sign"];
//    [WXApi sendReq:request];
//}
//
//#pragma mark - WXApiDelegate
//- (void)onResp:(BaseResp *)resp
//{
//    // 向微信请求授权后,得到响应结果
//    if ([resp isKindOfClass:[SendAuthResp class]])
//    {
//        SendAuthResp *temp = (SendAuthResp *)resp;
//        NSString *accessUrlStr = [NSString stringWithFormat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", kWeixinBaseUrl, kWeiXinAppId, kWeiXinAppSecret, temp.code];
//        
//        //发送请求
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//        [manager GET:accessUrlStr parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
//         {
//             NSLog(@"请求access的response = %@", responseObject);
//             NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
//             NSString *accessToken = [accessDict objectForKey:@"access_token"];
//             NSString *openID = [accessDict objectForKey:@"openid"];
//             NSString *refreshToken = [accessDict objectForKey:@"refresh_token"];
//             // 本地持久化，以便access_token的使用、刷新或者持续
//             if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""])
//             {
//                 [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:kWeiXinAccessToken];
//                 [[NSUserDefaults standardUserDefaults] setObject:openID forKey:kWeiXinOpenId];
//                 [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:kWeiXinRefreshToken];
//                 [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
//             }
//             [self wechatLoginByRequestForUserInfo];
//         }
//             failure:^(NSURLSessionTask *operation, NSError *error)
//         {
//             NSLog(@"获取access_token时出错 = %@", error);
//         }];
//        
//    }
//    else if ([resp isKindOfClass:[PayResp class]])
//    {
//        PayResp* response = (PayResp*)resp;
//        
//        switch(response.errCode)
//        {
//            case WXSuccess:
//                NSLog(@"发起支付成功");
//                
//                //如果是从原生发起的支付。
//                //注意！⚠️这里的逻辑需要升级，因为现在在两个地方调用了 checkStatus ,一个是这里，一个是在 payCallback 之后的代码里⚠️ 我觉得只调用一次比较好
//                if(payView != nil)
//                {
////                    [ThirdPartAlipay checkStatus:buyhistoryid callback:^(BOOL status, NSString *date)
////                     {
////                         if(status)
////                         {
////                             NSLog(@"enddate: %@", date);
//////                             [SettingDone setVipEndTime:date];
////
////                             //////////////////////////////////////////////////////////////////////////////////////
//////                             ReactLittleWindowController* react = [[ReactLittleWindowController alloc]init];
//////                             react.parentView = payView;
//////                             react.type = WindowTypePayDone;
//////                             [react showup];
////                             //////////////////////////////////////////////////////////////////////////////////////
////                         }
////                         else
////                         {
//////                             NSLog(@"支付失败");
//////                             [payView showHUDError:NSLocalizedString(@"payFailed", @"")];
//////                             [payView hideHUD];
////                             
//////                             ReactLittleWindowController* react = [[ReactLittleWindowController alloc]init];
//////                             react.parentView = payView;
//////                             react.type = WindowTypePayFailed;
//////                             [react showup];
////                         }
////                     }];
//                }
//                //如果是从 REACT 发起的支付
//                else if(reactView != nil)
////                    [(ReactCenterViewController*)reactView payCallback:true buyId:buyhistoryid];
//                
//                break;
//                
//            default:
//                NSLog(@"支付失败，retcode=%d",resp.errCode);
//            
//                if(payView != nil)
//                {
////                    [payView showHUDError:NSLocalizedString(@"payFailed", @"")];
////                    [payView hideHUD];
////                    
////                    ReactLittleWindowController* react = [[ReactLittleWindowController alloc]init];
////                    react.parentView = payView;
////                    react.type = WindowTypePayFailed;
////                    [react showup];
//                }
//                else
////                    [(ReactCenterViewController*)reactView payCallback:false];
//                break;
//        }
//
//    }
//    
//}
//
//- (void)onReq:(BaseReq *)req
//{
//    
//}
//
//// 获取用户个人信息（UnionID机制）
//- (void)wechatLoginByRequestForUserInfo
//{
//    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:kWeiXinAccessToken];
//    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:kWeiXinOpenId];
//    NSString *userUrlStr = [NSString stringWithFormat:@"%@/userinfo?access_token=%@&openid=%@", kWeixinBaseUrl, accessToken, openID];
//    
//    //发送请求
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//    [manager GET:userUrlStr parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
//     {
//         //请求成功后内容
//         NSLog(@"请求用户信息的response = %@", responseObject);
//         NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
//         
////         BOOL check = [MGCLoginRegisterViewController genericLoginProcess:[WechatEntity initWithDict:accessDict]];
//         
////         if(check)//useless
////         {
////             UIApplication.sharedApplication.delegate.window.rootViewController = [[MGCTabBarController alloc] init];
////         }
//     }
//         failure:^(NSURLSessionTask *operation, NSError *error)
//     {
//         NSLog(@"获取access_token时出错 = %@", error);
//     }];
//    
//}
//
//@end
